﻿<?php
/**
 * Browser controller
 *
 * Sewiki is a experimental software for course
 * Software Engineering in HIT and it's devoloped
 * upon CodeIgniter Framework. More infomation of
 * the framework, please vist http://codeigniter.com/
 *
 * Maybe this controller is too large and I should
 * split it
 * 
 * @package  : CodeIgniter
 * @category : controllers/browser
 * @author   : Oneplus <oneplus.lau@gmail.com>
 * @date     : 2011-06-13
 */
class Browser extends CI_Controller {
	/**
	 * The constructor
	 *
	 * @access : public
	 * @return : void
	 */
	function __construct() {
		parent::__construct();
		$this->load->model('user');
		$this->load->model('book');
		$this->load->model('chapter');
		$this->load->model('edition');
		$this->load->model('menu');
		$this->load->model('parser');
		$this->load->database();
	}
	
	/**
	 * Method BookList
	 *
	 * Main controller method for browse book list
	 *
	 * @access : public
	 * @return : void
	 */
	public function bookList() {
		// step i trace user's browse path with model menu 
		$this->menu->releaseBook();
		$this->menu->releaseChapter();
		$this->menu->releaseEdition();

		// step ii prepare books information
		$books = $this->db->get('books');
		$data = array();

		foreach($books->result() as $book) {
			$bid  = $book->bid;
			$uid  = $this->session->userdata('uid');
			$auid = $book->uid;
			
			$this->db->select('username');
			$user  = $this->db->get_where('users', array('uid' => $auid));
			$admin = $user->row();
			
			$book_info = array(
				'bid'                => $bid,
				'title'              => $book->title,
				'description'        => $book->description,
				'admin'              => $admin->username,
				'chapter_detail_url' => site_url('browser/Browser/chapterList/' . strval($bid)),
				'operators'          => array());

			// step iii prepare the operators
			//  if current user is editor
			//		if his is not the editor for certain book
			//			he can <<apply>> for join
			//  if current user is admin
			//		if his ia the admin for the certain book
			//			he can <<modify book info>>,
			//			<<create new chapter>> for the book
			//  else
			//		god damn the ghost >:D
			if($this->user->role() == 1 && $this->user->isEditorForBook($uid, $bid) == false) {
				$book_info['operators'] = array(
					array(
						'op_url'  => site_url('editor/applicationManager/apply/' . strval($bid)),
						'op_name' => '申请加入编辑'));
			}
			else if($this->user->role() == 2 && $this->user->isAdminForBook($uid, $bid) == true) {
				$book_info['operators'] = array(
					array(
						'op_url'  => site_url('admin/BookManager/modifyBook/' . strval($bid)),
						'op_name' => '修改图书信息'),
					array(
						'op_url'  => site_url('admin/ChapterManager/createChapter/' . strval($bid)),
						'op_name' => '创建新章节'));
			}
			else {
				$book_info['operators'] = array();
			}
			
			array_push($data, $book_info);
		}

		// maybe something of no-use
		if($this->session->userdata('role') == 1)
			$adminAuth = 'hide';
		else
			$adminAuth = '';

		$books = array(
			'adminAuth' => $adminAuth,
			'books'     => $data);
		
		// step iv load book list view
		$this->load->view('browser/bookList', $books);
	}
	
	/**
	 * Chapter List Controller
	 * 
	 * Main controller method for browse chapter list
	 * of a certain book
	 *
	 * @access : public
	 * @param  : int, bid
	 * @return : void
	 */
	public function chapterList($bid) {
		// step i trace user's browse path with model menu
		$this->menu->setBook($bid);
		$this->menu->releaseChapter();
		$this->menu->releaseEdition();
	
		// step ii prepare chapters information
		$book      = $this->book->getBook($bid);
		$uid       = $this->session->userdata('uid');
		$this->db->order_by('number', 'asc');
		$chapters  = $this->db->get_where('chapters', array('bid' => $bid));
		
		$data      = array();

		foreach($chapters->result() as $chapter) {
			$cid = $chapter->cid;
			$chapter_info = array(
				'title'                    => $chapter->title,
				'description'              => $chapter->description,
				'edit_state'               => $chapter->edit_state,
				'create_time'              => $chapter->create_time,
				'number'                   => $chapter->number,
				'content'                  => $chapter->content);
				
			// step iii prepare the operators
			//  if current user is editor
			//		if his is the editor for certain book
			//			he can <<browse editions>>,
			//			<<join in discuss>> for the certain chapter
			//			if this book is editable
			//				he can <<create new blank edition>>
			//  if current user is admin
			//		if his is the admin for the certain book
			//			he can <<browse editions>>,
			//			<<join in discuss>> for the book
			//  else
			//		let the ghost make it himself >:D
			if($this->user->role() == 1 && $this->user->isEditorForBook($uid, $bid) == true) {
				$chapter_info['operators'] = array(
					array(
						'op_url'  => site_url('browser/Browser/editionList/' . strval($cid)),
						'op_name' => '浏览版本信息'),
					array(
						'op_url'  => site_url('forum/Forum/thread/' . strval($cid)),
						'op_name' => '讨论'));
						
				if($chapter_info['edit_state'] == 0) {
					array_push($chapter_info['operators'], array(
						'op_url'  => site_url('editor/EditionManager/createBlankEdition/' . strval($cid)),
						'op_name' => '创建空白新版本'));
				}
			}
			else if($this->user->role() == 2 && $this->user->isAdminForBook($uid, $bid) == true) {
				$chapter_info['operators'] = array(
					array(
						'op_url'  => site_url('browser/browser/editionList/' . strval($cid)),
						'op_name' => '浏览版本信息'),
					array(
						'op_url'  => site_url('forum/Forum/thread/' . strval($cid)),
						'op_name' => '讨论'));
			}
			else {
				$chapter_info['operators'] = array();
			}
			
			array_push($data, $chapter_info);
		}
		
		if($this->user->isAdminForBook($uid, $bid) == false)
			$adminAuth = 'hide';
		else 
			$adminAuth = '';

		$data = array(
			'adminAuth' => $adminAuth,
			'book'      => $book,
			'chapters'  => $data);

		// step iv load book list view
		$this->load->view('browser/chapterList', $data);
	}
	
	/**
	 * Edition List Controller
	 *
	 * Main controller method for browse edition list
	 * of a certain chapter
	 *
	 * @access : public
	 * @param  : int, cid
	 * @return : void
	 */
	public function editionList($cid) {
		// step i trace user's browse path with model menu
		$this->menu->setChapter($cid);
		$this->menu->releaseEdition();
		
		// step ii prepare chapter information
		$data = array();
		$chapter  = $this->chapter->getChapter($cid);
		
		// step iii prepare editions information
		$editions = $this->db->get_where('editions', array('cid' => $cid));
		foreach($editions->result() as $edition) {
			$uid    = $edition->uid;
			$eid    = $edition->eid;
			$cid    = $edition->cid;
			$bid    = $chapter['bid'];
			$user   = $this->db->get_where('users', array('uid' => $uid));
			$editor = $user->row()->username;
			
			$edition_info = array(
				'eid'          => $eid,
				'create_time'  => date("Y-m-d", strtotime($edition->create_time)),
				'editor'       => $editor,
				'comment'      => $edition->comment,
				'public_level' => $edition->public_level,
				'content'      => nl2br($this->parser->shorten($edition->content, 250)));
				
			if($edition_info['public_level'] == 0 
			&& $this->user->isOwnerOfEdition($this->session->userdata('uid'), $eid) == false)
				continue;
			
			
			// step iv prepare the operators
			//  if current chapter is editable
			//  	if current user is editor
			//			if his is the editor for certain book
			//				he can <<create history editions>>,
			//				if his is the author of a certain edition
			//					he can <<submit>> this edition
			//  else
			//		:(
			if($chapter['edit_state'] == 0) {
				if($this->user->role() == 1 && $this->user->isEditorForBook($this->session->userdata('uid'), $bid) == true) {
					$edition_info['operators'] = array(
						array(
							'op_url'  => site_url('editor/EditionManager/createHistoryEdition/' . strval($cid) . '/' . strval($eid)),
							'op_name' => '从这个版本创建'));
							
					if($this->user->isOwnerOfEdition($this->session->userdata('uid'), $eid) == true) {
						array_push($edition_info['operators'], array(
							'op_url'  => site_url('editor/SubmissionManager/submit/' . strval($eid)), 
							'op_name' => '提交这一版本'));
					}
				}
				else {
					$edition_info['operators'] = array();
				}
			}
			else {
				$edition_info['operators'] = array();
			}
			
			array_push($data, $edition_info);
		}
		$data = array(
			'chapter'  => $chapter,
			'editions' => $data);
		$this->load->view('browser/editionList', $data);
	}
	
	/**
	 * Method Edition Detail
	 *
	 * Main controller method for browse edition detail
	 * of a certain edition
	 *
	 * @access : public
	 * @param  : eid
	 * @return : void
	 */
	public function EditionDetail($eid) {
		// step i prepare edition information
		$edition = $this->edition->getEdition($eid);
		$cid     = $edition['cid'];
		$uid     = $edition['uid'];
		$eid     = $edition['eid'];
		$user    = $this->user->getUser($uid);
		$chapter = $this->chapter->getChapter($cid);
		$edition['content']  = nl2br($edition['content']);
		$edition['username'] = $user['username'];
		$data = array(
			'edition'   => $edition,
			'chapter'   => $chapter);
		
		// step ii prepare operators
		if($chapter['edit_state'] == 0) {
			$data['operators'] = array(array(
				'op_url'  => site_url('editor/EditionManager/createHistoryEdition/' . strval($cid) . '/' . strval($eid)),
				'op_name' => '从这个版本创建'));
			if($this->user->isOwnerOfEdition($this->session->userdata('uid'), $eid) == true) {
				array_push($data['operators'], array(
					'op_url'  => site_url('editor/SubmissionManager/submit/' . strval($eid)), 
					'op_name' => '提交这一版本'));
			}
		}
		else {
			$data['operators'] = array();
		}
		
		// step iii load view
		$this->load->view('browser/edition', $data);
	}
	
	/**
	 * Method Application List
	 *
	 * Main controller method for browse application
	 *
	 * @access : public
	 * @return : void
	 */
	public function applicationList() {
		// step i check authority
		if($this->user->role() != 2) {
			$this->session->set_userdata(array('msg' => '权限不够，不能浏览申请列表'));
			redirect('main');
		}
		
		// step ii prepare application infomation
		$uid   = $this->session->userdata('uid');
		$books = $this->db->get_where('books', array('uid' => $uid));
		
		$data  = array();
		foreach($books->result() as $book) {
			$bid = $book->bid;
			$applications = $this->db->get_where('applications', array('bid' => $bid));
			foreach($applications->result() as $application) {
				$aid          = $application->aid;
				$uid          = $application->uid;
				$user         = $this->db->get_where('users', array('uid' => $uid));
				$applyEditor  = $user->row()->username;
				$applyMessage = $application->message;
				$apply = array(
					'apply_editor'  => $applyEditor,
					'apply_message' => $applyMessage,
					'accept_url'    => site_url('admin/applicationManager/accept/' . strval($aid)),
					'decline_url'   => site_url('admin/applicationManager/decline/' . strval($aid)));

				array_push($data, $apply);
			}
		}
		
		// step iii load view
		$data = array('applications' => $data);
		$this->load->view('browser/applicationList', $data);
	}
	
	/**
	 * Method Submission List
	 *
	 * Main controller method for browse submission
	 *
	 * @access : public
	 * @return : void
	 */
	public function submissionList() {
		// step i check authority
		if($this->user->role() != 2) {
			$this->session->set_userdata(array('msg' => '权限不够，不能浏览提交列表'));
			redirect('main');
		}
		
		// step ii prepare submission
		$auid        = $this->session->userdata('uid');
		$submissions = $this->db->get_where('submissions', array('auid' => $auid));
		
		$data  = array();
		foreach($submissions->result() as $submission) {
			$sid          = $submission->sid;
			$uid          = $submission->uid;
			$eid          = $submission->eid;
			$user         = $this->user->getUser($uid);
			$submitEditor = $user['username'];
			$edition      = $this->edition->getEdition($eid);
			$submit = array(
				'submit_editor' => $submitEditor,
				'content'       => nl2br($edition['content']),
				'accept_url'    => site_url('admin/submissionManager/accept/' . strval($sid)),
				'decline_url'   => site_url('admin/submissionManager/decline/' . strval($sid)));
			
			array_push($data, $submit);
		}
		
		// step iii load view
		$data = array('submissions' => $data);
		$this->load->view('browser/submissionList', $data);
	}
	/**
	 *
	 *
	 *
	 *
	 *
	 */
	public function messageList() {
		if($this->session->userdata('role') != 1) {
			$this->session->set_userdata(array('msg' => '权限不够，不能消息盒子'));
			redirect('main');
		}
		
		$data = array();
		$data['msgs'] = array();
		$this->db->order_by('create_time asc');
		$query = $this->db->get_where('messages', array('uid' => $this->session->userdata('uid')));
		
		foreach($query->result() as $row) {
			$msg_info = array(
				'msg'       => $row->msg,
				'operators' => array(array(
					'op_name' => '知道了',
					'op_url'  => site_url('editor/messageManage/accept/' . strval($row->mid))
				))
			);

			array_push($data['msgs'] , $msg_info);
		}
		
		$this->load->view('browser/messageList', $data);
	}
}
?>
